package com.song.onetomany.web;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageInfo;
import com.song.onetomany.pojo.User;
import com.song.onetomany.service.UserService;
import com.song.onetomany.service.impl.UserServiceImpl;
import com.song.onetomany.util.ThUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.web.IWebExchange;
import org.thymeleaf.web.servlet.JakartaServletWebApplication;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 宋伟宁
 * @Date 2023/9/11
 * @Version 1.0
 **/
@WebServlet(urlPatterns = {"/delete","/list","/toadd","/save","/find","/findById"})
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String servletPath = req.getServletPath();
        System.out.println("请求的路径是："+servletPath);
        IWebExchange webExchange = JakartaServletWebApplication.buildApplication(getServletContext()).buildExchange(req, resp);
        WebContext webContext = new WebContext(webExchange);

        PrintWriter out = resp.getWriter();

        //创建一个日期转换器
        DateConverter dateConverter = new DateConverter();
        //设置格式
        dateConverter.setPatterns(new String[]{"yyyy-MM-dd"});
        //注册格式
        ConvertUtils.register(dateConverter, Date.class);


        switch (servletPath){
            case "/delete"->{
                String ids = req.getParameter("ids");
                out.print(JSON.toJSONString(this.userService.delete(ids)));
                out.close();
            }
            case "/findById" ->{
                String id = req.getParameter("id");
                Map map = new HashMap();
                //封装要修改的对象到map中：key：user
                map.put("user", this.userService.findUserBy(id));
                //封装角色集合
                map.put("roles",this.userService.roles());
                out.print(JSON.toJSONString(map));
            }
            case "/find"->{
                String id = req.getParameter("id");
                webContext.setVariable("id",id);
                ThUtils.print("/view/update.html",webContext,resp);
            }
            case "/save"->{
                //接收角色
                String[] ids = req.getParameterValues("ids");
                Map<String, String[]> map = req.getParameterMap();
                User user=new User();
                //接收用户
                try {
                    BeanUtils.populate(user,map);
                    //新增用户：user，roles
                   if(this.userService.save(user,ids)){
                       resp.sendRedirect("list");
                   }
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e);
                }
            }
            case "/toadd" ->{
              //角色集合
              webContext.setVariable("roles",this.userService.roles());
              //转发数据到页面
                ThUtils.print("/view/add.html",webContext,resp);
            }
            case "/list"->{
                String offset = req.getParameter("offset");
                String pagesize= req.getParameter("pagesize");
                PageInfo<User> pageInfo = this.userService.page_user(offset, pagesize);
                webContext.setVariable("pager",pageInfo);
                //webContext.setVariable("users",this.userService.users());
                ThUtils.print("/view/list.html",webContext,resp);
            }
        }

    }
}
